import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/login'
// 通过路由将用户列表组件引入
import Users from '@/components/user/users'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    redirect: '/welcome', // 路由重定向
    component: () => import('@/components/home'),
    children: [
      {
        path: '/welcome',
        component: () => import('@/components/welcome')
      },
      {
        path: '/users',
        component: Users
      }
    ]
  }

]

const router = new VueRouter({
  routes
})

// 挂载路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  // 如果不是去首页，判断sessionStore有没有token
  const gettoken = window.sessionStorage.getItem('token')
  if (!gettoken) return next('/login')
  next()
})

export default router
